use diesel::prelude::*;
use diesel::{MysqlConnection, QueryDsl};

use crate::database::{
    schema::{post, tag},
    table::{post::model::Post, tag::model::Tag},
    DbError,
};

pub struct PostWithAuthor {
    pub post: Post,
    pub author: Tag,
}

pub fn read_count_from_offset(
    conn: &mut MysqlConnection,
    count: i64,
    offset: i64,
) -> Result<Vec<PostWithAuthor>, DbError> {
    let select_rows = tag::table
        .inner_join(post::table)
        .select((Post::as_select(), Tag::as_select()))
        .order(post::id.desc())
        .limit(count)
        .offset(offset)
        .load(conn)?;
    let posts = select_rows
        .into_iter()
        .map(|(post, author)| PostWithAuthor { post, author })
        .collect();
    Ok(posts)
}
